<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir(dirname(__FILE__));

include_once $path."/../lib/core.class.php";


class ccontrl extends IPlugin 
{
        var $pagespool;
    
        
    function ccontrl($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->pagespool = null;
        $this->initialize();

    }
    
    function getPluginTag() { return "ccontrl"; }
    function getPluginName() { return "Ccontrl Page plugin"; }
    function getPluginVersion() { return "1.0.0"; }

    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Client control plugin"; } break;
            case "MenuTitle" : { return "ccontrl"; } break;
        };
        return $result;
    }
    
    function initialize()
    {
        $this->pagespool = array();
        if ($handle = opendir($this->tplfolder))
        {
            while (false !== ($file = readdir($handle)))
            {
                if("."==$file || ".."==$file || !file_exists($this->tplfolder."/".$file))
                {
                    continue;
                }
                $fl = split("\.", $file);
                $this->pagespool[] = $fl[0];
            }
            closedir($handle);
        }
        $this->pagespool = array_flip($this->pagespool);
        $core = &getCoreInstance();
        $core->setValues("catalogpage_url", "?".$this->getURL()."&page=");
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
    
        $core = &getCoreInstance();
        $mail = $core->getSnippet("email");
        $render = &$core->framework->smarty;
        $db = &$core->getProperty("db");
        
// --------<START> | Added by Gendich |  " Actions on WHISH LIST     " -------------...
        
        if (isset($_GET["event"]))
        {
            $wish_list=$_SESSION[wish_list];
            $id = $_GET["pid"];
                        $cid = $_SESSION[cc][client_id];
        switch ($_GET["event"]) {
            case "add": {
                $qty = 1;
                if($id>0 && $qty>0)
                {
                    if(isset($wish_list[$id]))
                    {
                        $wish_list[$id]["qty"] += $qty;
                        if(0 == $wish_list[$id]["qty"])
                        {
                            unset($wish_list[$id]);
                        }
                    }
                    else
                    {
                        $core = &getCoreInstance();
                        $db = $core->getProperty("db");
                        $z = $db->getRow("select parent_id, our_price, title, img_small from catalog where catalog_id={$id}");
                        $wish_list[$id] = array(
                                    "qty" => $qty,
                                    "price" => $z["our_price"],
                                    "title" => $z["title"],
                                    "thumbnail" => $z["img_small"],
                                    "pid" => $z["parent_id"],
                                    );
                    }
                    
                }
            } break;
            
            case "buy": {
                $cart = &$_SESSION["cart"];
                if(isset($cart[$id]))
                    {
                        $cart[$id]["qty"] += $wish_list[$id]["qty"];
                        $stock=$db->getone("select sum(qty) from store_history where catalog_id=$id");
                        if ($cart[$id]["qty"] > $stock) 
                        {   // ALARMA !!!
                            $cart[$id]["qty"] = $stock;
                            $GLOBALS[result_recalculate]="<br><font color=red>Sorry, but some qty out of stock.</font> You may <a href=\"?path=staticpage&page=contact_us\">ask us</a>, when goods appears in stock again.<br>";
                        }
                    }
                    else
                    {
                        $cart[$id]=$wish_list[$id];
                    }
                    $cart[$id][warranty]=0;
                    
                $_SESSION["cart"]=$cart;
                if($id>0)
                {
                    unset($wish_list[$id]);
                }
                header("location: ?path=cart");
            } break;
        
            case "del": {
                if($id>0)
                {
                    unset($wish_list[$id]);
                }
            } break;
            
            case "recalculate": {
                if (isset($_POST["qty"])){
                    foreach ($_POST["qty"] as $k => $v)
                    {
                        $wish_list[$k]["qty"] = $v;
                    }
        }
            } break;
        }
            
                if (!isset($cid))
                        $cid = 0;            
            $wish_list_db=str2db(serialize($wish_list));
            $db->exec("update clients set wish_list='$wish_list_db' where client_id=$cid");
///     debug("update clients set wish_list='$wish_list_db' where client_id=$cid");
            $_SESSION[wish_list]=$wish_list;
                                
            }
            //debug($_SESSION["wish_list"]);
            //debug($wish_list_db);
       // }
        
        
        
// --------<END>   | Added by Gendich | ---------------------------------------------///                   
 
        switch ($_POST["event"]) {

           
            case "doUpdatePayment": 
            {
                        unset($_POST['event'],$_POST['submit']);
                        $id = $this->updatecd($this->getSessionCc(),$_POST,&$db);               
                        $this->setmsgbox('Payment details changed');
                        @header("location: ./?".'path=ccontrl');
            }break;
    
                  
            case "doRemindPassword": 
            {
                                /* Remind password */
                                unset($_POST['event']);
                
                                if($_POST['remind_email'] != ''){
                
                                        $client_id = $this->is_email_inDb($_POST['remind_email'],$db);
                                        if ($client_id > 0){
                                                $new_pass = genPassword();
                                                $password = md5($new_pass);
                                                $cdarray = array('client_password' => $password);
                                                $id = $this->updatecd($client_id,$cdarray,&$db);                
                                        }
                                }
                                if ($client_id > 0){
                                $msg = "
                                        <html>
                                        <body>
                                        <b>BigAppleJewels.com account new password:</b>
                                        <br />
                                        Login: {$_POST[remind_email]}
                                        <br />
                                        Password: {$new_pass}
                                        <body>
                                        </html>";
                
                                        $emailfrom = $core->config["info_email"];
                                        $params = array(
                                        "html" => "1",            
                                        "from" => "{$emailfrom}",
                                        "to"   => "{$_POST[remind_email]}", 
                                        "body" => "$msg",
                                        "subject" => "BigAppleJewels.com password reminder");
                
                                        $mail->Render($params);       
                                
                                $this->setmsgbox('Your new password sent to your e-mail');
                                        $render->assign("ps", 'Your new password sent to your e-mail');       
                
                                }
                                /* else nothing is done */              
                
                                if ($n > 0) {
                                        $this->setSessionCc(0);
                                                $render->assign("ps", 'Error');       
                                }
            } break;   



            case "doLogin": {
                        /* check client login */
                        unset($_POST['event']);
                        $islogin = $this->checklogin(str2db($_POST['cc_login']),str2db($_POST['cc_passw']),$db);
                                        
                        $tpm = $this->setSessionCc($islogin);
                        $n   = $this->getSessionCc();
                        if ($n > 0) {
                                header("location: ./?".'path=ccontrl');
                                    } else {$_SESSION[login_error]="Login faild";}
                   } break;   
        
                        case "RegisterNewClient": {
                        /* add client */
                        unset($_POST['event']);
                        unset($_POST['submit']);
        
                        
                        $x = $this->insertcd(Arraystr2db($_POST),&$db);
                                if ($x == '-1'){
                                        header("location: ./?".'path=ccontrl&page=alredyindb');
                                }
                                else{
                                $this->setSessionCc($x);
                                @header("location: ./?".'path=ccontrl');
                                }
        
            } break;
            
            
               

            case "doUpdateAccount": {
                        unset($_POST['event']);
                            $acount = $this->getallcd($this->getSessionCc(),$db);
                        $cdarray = array();
                                if ($acount['client_password'] == md5($_POST['client_password'])){
                
                                        $cdarray = array('client_name' => $_POST['client_name'],
                                                         'client_email' => $_POST['client_email']);
                                
                                        if ($_POST['new_client_password'] != '' and $_POST['new_client_password'] == $_POST['new_client_password_repeat']){
                                                $cdarray['client_password'] = $_POST['new_client_password'];    
                                        }       
            
                                $id = $this->updatecd($this->getSessionCc(),$cdarray,&$db);             
                                header("location: ./?".'path=ccontrl');
                                $this->setmsgbox('Account details changed');
                                }
                                else{
                                $id = '-1';
                                $this->setmsgbox('Wrong password');
                                }
                        
            }break;
            
            
            
            
            case "SubmitReturnProductCenter" :
            {
                $arr_orders = array();
                foreach($_POST['qty'] as $key => $num)
                {
                    if (0 == $num)
                    {
                        unset($_POST['qty'][$key]);
                    }
                    else
                    {
                        $ord_cat = split("-", $key);
                        if (0 == $arr_orders[$ord_cat[0]])
                            $arr_orders[$ord_cat[0]] = array();
                        $arr_orders[$ord_cat[0]][$key] = array();
                        $arr_orders[$ord_cat[0]][$key]['catalog_id'] = $ord_cat[1];
                        $arr_orders[$ord_cat[0]][$key]['qty'] = $num;
                                        }
                }
                        if (count($_POST['qty']) > 0)
                {
                    $sql = "select client_cctype, client_ccnumber, client_ccholdername, client_cccvv, client_billing_name, client_billing_adress1,";
                    $sql .= " client_billing_adress2, client_billing_city, client_billing_state, client_billing_zip, client_billing_country, client_email,";
                    $sql .= " client_phone, client_shipping_name, client_shipping_adress1, client_shipping_adress2, client_shipping_city, client_shipping_state,";
                    $sql .= " client_shipping_zip, client_shipping_country";
                    $sql .= " from clients where client_id = {$_SESSION[cc][client_id]}";
                    
                    $info_client = $db->getAll($sql);
                    $info_client = $info_client[0];
                    
                    foreach ($arr_orders as $from_order => $order)
                    {
                        $db->Exec("insert into orders(cctype, ccnumber, ccholdername, cccvv, pubdate, fname, lname, company, address1, address2, city, state, zip, country, email, phone,
                                                findus, findother,
                                                sfname, slname, saddress1, saddress2, scity, sstate, szip, scountry,
                                                price, status, shipment,discount, type_order, from_order)
                                        values( ?, ?, ?, ?, now(),
                                                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                                                ?, ?,
                                                ?, ?, ?, ?, ?, ?, ?, ?,
                                                ?, ?, ?, ?, ?, ?)", 0, array(
                                array($info_client['client_cctype'], $info_client['client_ccnumber'], $info_client['client_ccholdername'], $info_client['client_cccvv'],
                                      $info_client['client_billing_name'], '', '', $info_client['client_billing_adress1'], $info_client['client_billing_adress2'],
                                      $info_client['client_billing_city'], $info_client['client_billing_state'], $info_client['client_billing_zip'], 
                                      $info_client['client_billing_country'], $info_client['client_email'], $info_client['client_phone'], '', '',
                                      $info_client['client_shipping_name'], '', $info_client['client_shipping_adress1'], $info_client['client_shipping_adress2'],
                                      $info_client['client_shipping_city'], $info_client['client_shipping_state'], $info_client['client_shipping_zip'], 
                                      $info_client['client_shipping_country'], '', 1, '', '', 'ret', $from_order)));

                        $id_order = $db->getInsertID();
                        
                        $sql = "insert into clients_orders (cl_id, order_id) " .
                                "values ({$_SESSION[cc][client_id]}, {$id_order})";
                        $db->Exec($sql);

                        $price = 0;
                                                $purchaseitems_discount = 0;
                        foreach ($order as $index => $data_catalog)
                        {
                            $sql = "select catalogid, price, title, image, warranty, purchaseitems_discount from purchaseitems where order_id = {$from_order} and catalogid = {$data_catalog[catalog_id]}";
                            
                            $info_prod = $db->getAll($sql);
                            $info_prod = $info_prod[0];

                            $sql = "insert into purchaseitems (order_id, catalogid, price, qty, title, image, warranty, reason)";
                            $sql .= " values({$id_order}, {$info_prod[catalogid]}, {$info_prod[price]}, {$data_catalog[qty]}";
                            $sql .= ", '{$info_prod[title]}', '{$info_prod[image]}', {$info_prod[warranty]}, '" . str2db($_POST['reason'][$index]) . "')";
                            $db->Exec($sql);
                            
                            $price += $data_catalog['qty'] * ($info_prod['price'] - $info_prod['purchaseitems_discount']);
                            $purchaseitems_discount+=$info_prod['purchaseitems_discount'];
                            $sql = "insert into store_history (catalog_id, date, action, qty)";
                            $sql .= " values({$info_prod[catalogid]}, now(), 'return', {$data_catalog[qty]})";
                            $db->Exec($sql);
                        }
                        //--- balance client add ++++++    [
                                                $sql = "update clients set balance = balance + $price where client_id = {$_SESSION[cc][client_id]}";
                                                $db->Exec($sql);
                                                //--- balance client add ++++++    ]
                        $sql = "update orders set price = '{$price}', discount='$purchaseitems_discount' where id = {$id_order}";
                        $db->Exec($sql);
                    }
                }
            }
            break;

       }

   }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $render = &$core->framework->smarty;
        $db = &$core->getProperty("db");
        
        switch ($_G["page"]) {

            case "printorder" :
    
                        if ($this->getSessionCc() > 0)
                    {     
                        $this->RenderPrintPopupOrder($core, $render, $db);
                        $page = "popupprint.tpl.php ";
                        }
                        else
                    {
                        $this->RenderAccountSetupPage($core, $render, $db);
                        $page = "accountsetup.tpl.php";
                        }
                    break;


            case "myorders" :
    
                        if ($this->getSessionCc() > 0)
                    {     
                        $this->RenderClientOrders($core, $render, $db);
                        $page = "myorders.tpl.php";
                        }
                        else
                    {
                        $this->RenderAccountSetupPage($core, $render, $db);
                        $page = "accountsetup.tpl.php";
                        }
                    break;


            case "payment_setup" :
    
                        if ($this->getSessionCc() <= 0) 
                    {     
                        $this->RenderLoginPage($core, $render, $db);
                        $page = "cclogin.tpl.php";
                    }
                        else
                    {
                        $this->RenderPaymentSetupPage($core, $render, $db);
                        $page = "paymentsetup.tpl.php";
                        }
                    break;

            case "billing" :
    
                        if ($this->getSessionCc() <= 0) 
                    {     
                        $this->RenderLoginPage($core, $render, $db);
                        $page = "cclogin.tpl.php";
                    }
                        else
                    {
                        $this->RenderPaymentSetupPage($core, $render, $db);
                        $page = "billing.tpl.php";
                        }
                    break;

            case "shipping" :
    
                        if ($this->getSessionCc() <= 0) 
                    {     
                        $this->RenderLoginPage($core, $render, $db);
                        $page = "cclogin.tpl.php";
                    }
                        else
                    {
                        $this->RenderPaymentSetupPage($core, $render, $db);
                        $page = "shipping.tpl.php";
                        }
                    break;

            case "ccard" :
    
                        if ($this->getSessionCc() <= 0) 
                    {     
                        $this->RenderLoginPage($core, $render, $db);
                        $page = "cclogin.tpl.php";
                    }
                        else
                    {
                        $this->RenderPaymentSetupPage($core, $render, $db);
                        $page = "ccsetup.tpl.php";
                        }
                    break;

    
    
    
            case "loged_acc_setup" :
    
                        if ($this->getSessionCc() <= 0)
                    {     
                        $this->RenderLoginPage($core, $render, $db);
                        $page = "cclogin.tpl.php";
                        }
                        else
                    {
                        $this->RenderAccountSetupPage($core, $render, $db);
                        $page = "accountsetup.tpl.php";
                        }
                    break;
        
            case "login" :
                        if ($this->getSessionCc() <= 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                        }
                        else
                    {
                        $this->RenderAccountPage($core, $render, $db);
                        $page = "account.tpl.php";
                        }
                    break;
    
            case "register" :
                    $this->RenderRegisterPage($core, $render, $db);
                    $page = "clientregistrationform.tpl.php";
                    break;
    
            case "account" :
                        if ($this->getSessionCc() < 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                        }
                        else
                    {
                        $this->RenderAccountPage($core, $render, $db);
                        $page = "account.tpl.php";
                        }
                    break;
    
            case "alredyindb" :
                    $this->RenderStatic();
                    $page = "accalreadyexist.tpl.php";
                    break;
    
    
            case "logout" :
                        $this->setSessionCc(0);
                        if(isset($_SESSION['secure']));
                           unset($_SESSION['secure']);

                        if(isset($_SESSION["cart"]));
                           unset($_SESSION["cart"]);


                    $page = "cclogout.tpl.php";
                        header("location: ./?");
    
                    break;
    
            case "passwreminder" :
                    $this->RenderStatic();
                    $page = "passwreminder.tpl.php";
                    break;

            case "view_history_products" :
                    if ($this->getSessionCc() < 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                    }
                    else
                    {
                        $this->renderViewHistoryProductsPage($core, $render, $db);
                        $page = "view_history_products.tpl.php";
                    }
                    break;
                    
// --------<START> | Added by Gendich |  " wish_list " -------------...
            case "view_wish_list" :
                    if ($this->getSessionCc() < 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                    }
                    else
                    {
                        $this->renderWishList($core, $render, $db);
                        $page = "view_wish_list.tpl.php";
                    }
                    break;
// ---------<END>  | Added by Gendich | ---------------------------------------------///                   
    
            case "return_center" :
                    if ($this->getSessionCc() < 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                    }
                    else
                    {
                        $page = $this->renderReturnCenterProductsPage($core, $render, $db);
                    }
                    break;

            case "order_details" :
                    if ($this->getSessionCc() < 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                    }
                    else
                    {
                        $page = $this->renderViewOrderDetailsPage($core, $render, $db);
                    }
                    break;
    
            default:
                    if ($this->getSessionCc() <= 0)
                    {     
                         $this->RenderLoginPage($core, $render, $db);
                         $page = "cclogin.tpl.php";
                                                        }
                    else
                    {
                                        
                                                $this->RenderAccountSetupPage($core, $render, $db);
                        $page = "accountsetup.tpl.php";
                    }
                    break;
        }
        

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }


/******************************************************************************************************************/
/************ Print order, popup  ********************************************************************************/
/******************************************************************************************************************/


function RenderPrintPopupOrder(&$core, &$render, &$db){
$this->renderViewOrderDetailsPage($core, $render, $db);

$render->assign("pop", 1);


}




/******************************************************************************************************************/
/************ Render View Order Details Page **********************************************************************/
/******************************************************************************************************************/

function renderViewOrderDetailsPage(&$core, &$render, &$db)
{
    $acount = $this->getallcd($this->getSessionCc(),$db);
    $render->assign("acount", $acount);

    if (0 != $db->getOne("select count(*) from orders  where id={$_GET[id]}"))
    {
        $z = $db->getAll("select * from orders where id={$_GET[id]}");
        $p = $db->getAll("select * from purchaseitems where order_id={$_GET[id]}");
        
        $z = ArrayDb2Str($z[0]);
        
        $price = 0;
        foreach($p as $k => $w)
        {
            if(file_exists($core->config["file_root"] . "/inventory/" . $p[$k]["image"]))
            {
                $p[$k]["image"] =  "/inventory/" . $p[$k]["image"];
            }
            else
            {
                $p[$k]["image"] = "/inventory/".  "noimage_small.jpg";
            }
            $value_warranty = $db->getOne("select warrantytype_price from products_warranty_types where warrantytype_id = {$p[$k][warranty]}");
            $p[$k]['warranty_num'] = @number_format($value_warranty * $p[$k]["qty"], 2, '.', ',');
            
            $price += $p[$k]["qty"]*$p[$k]["price"]+ $p[$k]['warranty_num'];;
            $p[$k]['price_num_prod'] = @number_format($p[$k]["qty"]*$p[$k]["price"],2,'.',',');
            $p[$k]['price_prod'] = @number_format($p[$k]["price"],2,'.',',');
            $p[$k]['reason'] = db2str($p[$k]["reason"]);
        }
        
        $z['ccnumber_num_simb'] = strlen($z['ccnumber']) - 4; 
        if($z['ccnumber_num_simb']<0) {$z['ccnumber_num_simb'] = 0;}

        $z['ccnumber'] = substr($z['ccnumber'], strlen($z['ccnumber']) - 4, 4);
        
        $z['discount'] = @number_format($z['discount'],2,'.',',');
        $z['price'] = @number_format($z['price'],2,'.',',');
        $id=$_GET[id];
        $render->assign("id", $id);
        $render->assign("order", $z);
        $render->assign("items", $p);
        $render->assign("price", @number_format($price,2,'.',','));
    
        $ship = $db->getrow("select * from shipment where shipment_id='" . $z['shipment'] . "'");
        $ship['shipment_price'] = @number_format($ship['shipment_price'],2,'.',',');
        $render->assign("shipment", $ship);
        
        $result = $db->getOne("select name from order_status where id = {$z[status]}");
        $render->assign("current_status", db2str($result));
        
        return "view_order_details.tpl.php";
    }
    else
    {
        header("location: ?" . $this->getURL() . "&page=myorders");
    }
}

/******************************************************************************************************************/
/************ Render Return Center Products ***********************************************************************/
/******************************************************************************************************************/

function renderReturnCenterProductsPage(&$core, &$render, &$db)
{
    $acount = $this->getallcd($this->getSessionCc(),$db);
    $render->assign("acount", $acount);
    
    if (isset($_POST["event"]) && "SubmitReturnProductCenter" == $_POST["event"])
    {
        //debug($_POST);
        $arr_orders = array();
        
        foreach($_POST['qty'] as $key => $num)
        {
            $ord_cat = split("-", $key);
            if (0 == $arr_orders[$ord_cat[0]])
                $arr_orders[$ord_cat[0]] = array();
                
            $index = count($arr_orders[$ord_cat[0]]);
            $arr_orders[$ord_cat[0]][$index] = array();
            $arr_orders[$ord_cat[0]][$index]['catalog_id'] = $ord_cat[1];
            $arr_orders[$ord_cat[0]][$index]['qty'] = $num;
            
            $sql = "select pubdate from orders where id = {$ord_cat[0]}";
            $arr_orders[$ord_cat[0]][$index]['pubdate'] = $db->getOne($sql);

            $sql = "select title from purchaseitems where order_id = {$ord_cat[0]} and catalogid = {$ord_cat[1]}";
            $arr_orders[$ord_cat[0]][$index]['title'] = $db->getOne($sql);
            
            $arr_orders[$ord_cat[0]][$index]['reason'] = $_POST['reason'][$key];
        }

        //debug($arr_orders);


        $render->assign("info_products_oders", $arr_orders);

        return "return_center_info.tpl.php";
    }
    else
    {
        $sql = "select id from order_status where lower(name) = 'completed'";
        $status = $db->getOne($sql);
                if($status != '')
        {
            $sql = "select purchaseitems.qty as qty, purchaseitems.catalogid, purchaseitems.title, orders.id as order_id, orders.pubdate
                    from clients_orders, purchaseitems, orders
                    where clients_orders.cl_id = {$_SESSION[cc][client_id]} and clients_orders.order_id = purchaseitems.order_id
                        and clients_orders.order_id = orders.id and orders.type_order = 'ord' and orders.status = {$status}";
            
            $info_products_oders = $db->getAll($sql);
        }

        $sql = "select sum(purchaseitems.qty) as qty, purchaseitems.catalogid, orders.id as order_id, orders.from_order
                from clients_orders, purchaseitems, orders
                where clients_orders.cl_id = {$_SESSION[cc][client_id]} and clients_orders.order_id = purchaseitems.order_id
                    and clients_orders.order_id = orders.id and orders.type_order = 'ret'
                group by orders.from_order, purchaseitems.catalogid";
        
        
        $info_products_return = $db->getAll($sql);
        $left_array = array();
                if (count($info_products_oders) >= 1)
        {
            foreach($info_products_oders as $prod)
            {
                if (0 == count($left_array[$prod['order_id']]))
                    $left_array[$prod['order_id']] = array();
                
                $index = count($left_array[$prod['order_id']]);
                $left_array[$prod['order_id']][$index] = array();
                $left_array[$prod['order_id']][$index]['qty'] = $prod['qty'];
                $left_array[$prod['order_id']][$index]['title'] = db2str($prod['title']);
                $left_array[$prod['order_id']][$index]['catalog_id'] = $prod['catalogid'];
                $left_array[$prod['order_id']][$index]['pubdate'] = $prod['pubdate'];
            }
                }
        $info_products_oders = $left_array;

        $left_array = array();
        foreach($info_products_return as $prod)
        {
            if (isset($info_products_oders[$prod['from_order']]))
            {
                foreach($info_products_oders[$prod['from_order']] as $index => $data_prod)
                {
                    if ($data_prod['catalog_id'] == $prod['catalogid'])
                    {
                        if ($prod['qty'] >= $data_prod['qty'])
                        {
                            unset($info_products_oders[$prod['from_order']][$index]);
                        }
                        else
                        {
                            $info_products_oders[$prod['from_order']][$index]['qty'] = $data_prod['qty'] - $prod['qty'];
                        }
                        break;
                    }
                }
                
                if (0 == count($info_products_oders[$prod['from_order']]))
                    unset($info_products_oders[$prod['from_order']]);
            }
        }

//        debug($info_products_oders);
//        debug($info_products_return);

    
        $render->assign("info_products_oders", $info_products_oders);
        
        return "return_center.tpl.php";
    }
}

/******************************************************************************************************************/
/************ Render View History Last Visit Products *************************************************************/
/******************************************************************************************************************/

function renderViewHistoryProductsPage(&$core, &$render, &$db)
{
    $acount = $this->getallcd($this->getSessionCc(),$db);
    $render->assign("acount", $acount);       


    $history_products = $core->getSnippet("historyproducts");
    $params_history_products = array
    (
        'prod_id' => "",
        'limit_records' => "",
        'user_id' => $_SESSION['cc']['client_id']
    );
    
    $arr_history = $history_products->getHistoryRecords($params_history_products);
    
    $hs = &$core->getSnippet("historylinks");
    $arr_info_products = array();
    
    foreach ($arr_history as $product)
    {
        $params = array(
            "startfrom" => $product['product_id'],
            "f_id" => "catalog_id",
            "f_parent" => "parent_id",
            "f_title" => "title",
            "table" => "catalog",
            "stopval" => 0, // root
            "url" => "?path=catalogpage&cid=###",
            "html_root" => "Home",
            "html_url" => "?path=catalogpage&cid=0",
            "html_separatop" => " :: ",
        );
        $hs_edit = $hs->Render($params);
        $arr_info_products[$product['product_id']]['hlinks'] = $hs_edit;
        
        $sql = "select catalog_id, title, img_small from catalog where catalog_id = " . $product['product_id'];
        $info_product = ArrayDb2Str($db->getAll($sql));
        $arr_info_products[$product['product_id']]['prod_info'] = $info_product[0];
        
        if (file_exists($core->config["file_root"] . "/inventory/" . $arr_info_products[$product['product_id']]['prod_info']['img_small']))
        {
            $arr_info_products[$product['product_id']]['prod_info']['img_small'] = "./inventory/" . $arr_info_products[$product['product_id']]['prod_info']['img_small'];
        }
        else
        {
            $arr_info_products[$product['product_id']]['prod_info']['img_small'] = "./img/no_image.jpg";
        }
    }

    $render->assign("arr_info_products", $arr_info_products);
    
    
}

/******************************************************************************************************************/
/************ Render Wish List Page *******************************************************************************/
/******************************************************************************************************************/

function renderWishList(&$core, &$render, &$db)
{
    $acount = $this->getallcd($this->getSessionCc(),$db);
    $render->assign("acount", $acount);       

    $client_id=$_SESSION[cc][client_id];
    
    $wish_list = $_SESSION["wish_list"];
    
    //debug($_SESSION["wish_list"]);
    //debug($_SESSION);
        
    $price=0;
    if (isset($_SESSION["wish_list"]) and count($_SESSION["wish_list"]) > 0 and $_SESSION["wish_list"]!="")
        {
        //debug($_SESSION["wish_list"]);
        foreach ($_SESSION["wish_list"] as $v)
        {
            $wish_list[$v[id]][qty_on_stock]=$db->getone("select sum(qty) from store_history where catalog_id=$v[id]");
            //debug($qty_on_stock);
            //debug($v);
                        if (file_exists($core->config["file_root"]."/inventory/".$v[thumbnail]) && is_file($core->config["file_root"]."/inventory/".$v[thumbnail])) {
                                list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$v[thumbnail]));
                                $default_w_size=60;
                                $default_h_size=67;
                                //debug($w_size,$h_size);
                                $size="";
                                if ($w_size>$h_size && $w_size>$default_w_size)
                                        $size=" width=\"{$default_w_size}px\" ";
                                if ($h_size>$w_size && $h_size>$default_h_size)
                                $size=" height=\"{$default_h_size}px\" ";
                                
                                $wish_list[$v[id]][thumbnail] = "<img $size src=\"inventory/".$v[thumbnail]."\" border=\"0\" >";
                        } else {
                                $wish_list[$v[id]][thumbnail] = "<img src='img/no_image.jpg' border=0 height=60/>";
                        }
                        //debug($wish_list[$v[id]][thumbnail]);
            $price+=$v[price]*$v[qty];
        }
        }
    //debug($wish_list);
    $render->assign("price", $price);
       
    $render->assign("wish_list", $wish_list);
    $render->assign("client_id", $this->getSessionCc());

    //$whish_list=unserialize($db->getone("select wish_list from clients where client_id=$client_id"));
         
     //debug($_GET,"get");  debug($_POST,"post");  
     //debug($_SESSION, "sisja");
    
    //$core = &getCoreInstance();
    $render->assign("host", $core->config['http_root']);
    if (isset($_GET["id"])){
    
    $from_catalog = $db->getone("select parent_id from catalog where catalog_id = $xid");       
    $render->assign("parent_cat", $from_catalog);
                       }
   
}
// --------<END>   | Added by Gendich | ---------------------------------------------///                   

/******************************************************************************************************************/

                        /////////////////////////////////////////
                        //                                     //
                        //        Login page render            //
                        //                                     //
                        /////////////////////////////////////////
    
                function RenderLoginPage(&$core, &$render, &$db){

                        $loginname = 'cc_login';
                        $passname  = 'cc_passw';
                        $formname  = 'cc_formn';
                        $eventnam  = 'event';
                        $eventval  = 'doLogin';


                        $render->assign("cc_input_login", $loginname);       
                        $render->assign("cc_input_formn", $formname);       
                        $render->assign("cc_input_passn", $passname);       
                        $render->assign("ename",          $eventnam);       
                        $render->assign("evalue",         $eventval);       
                                if (isset($_SESSION[login_error]))
                                {
                                        $render->assign("login_error", $_SESSION[login_error]="Login faild");
                                        unset($_SESSION[login_error]);
                                }
                }

                        /////////////////////////////////////////
                        //                                     //
                        //        Registration page render     //
                        //                                     //
                        /////////////////////////////////////////
    
                function RenderRegisterPage(&$core, &$render, &$db){
                        
                        
                        $today = getdate();
                        $today_year = $today['year'];
                        $today_mon  = $today['mon'];
                        
                        for($i=0;$i<6;$i++){
                                $goodyears[]['year'] = substr($today_year + $i,2,4);
                                
                                
                        }                       
                                
                                
                                for($i=1;$i<13;$i++){
                                        
                                        
                                                $goodmonths[]['months'] = $i;
                                        
                                }
                                
                                
                                
                                $i = 1;
                                foreach($goodmonths as $k => $v){
                                        if(strlen($v['months']) == 1){
                                                $m[$i] = '0'.$v['months'];      
                                        }
                                        else{
                                                $m[$i] = $v['months']; 
                                        }
                                        $i++;
                                }
                                
                                for($i=0;$i<$today_mon;$i++){
                                        unset($m[$i]);
                                }
                                                                
                                
                                //debug($m);
                                //debug($goodyears);
                                $render->assign("years",          $goodyears);       
                        $render->assign("months",         $m);       
                        
                        $render->assign("ename",          $eventnam);       
                        $render->assign("evalue",         $eventval);       
                        
                }


                        /////////////////////////////////////////
                        //                                     //
                        //        Acount page render           //
                        //                                     //
                        /////////////////////////////////////////
    
                function RenderAccountPage(&$core, &$render, &$db){

// --------<START> | Added by Gendich |  " " -------------...
                $id=$this->getSessionCc();
//                      debug($db->getone("select wish_list from clients where client_id={$id}"));
                        $_SESSION["wish_list"]=unserialize(db2str($db->getone("select wish_list from clients where client_id=$id")));
// --------<END>   | Added by Gendich | ---------------------------------------------///                   

                   $acount = $this->getallcd($this->getSessionCc(),$db);
                   $render->assign("acount",      $acount);       
                 //$render->assign("msg_box",     $this->getmsgbox());       
                   $this->unsetmsgbox();
                }


                        /////////////////////////////////////////
                        //                                     //
                        //        AcountSetup page render      //
                        //                                     //
                        /////////////////////////////////////////
    
                function RenderAccountSetupPage(&$core, &$render, &$db){
                   $event_on_change_account_settings = 'doUpdateAccount';
                   $acount = $this->getallcd($this->getSessionCc(),$db);
                   $render->assign("acount",      $acount);       
                   $site = $core->config["www_name"];
                   $render->assign("www",         $site);       
                // $render->assign("msg_box",     $this->getmsgbox());       
                   $render->assign("eventval",    $event_on_change_account_settings);       
                }



                        /////////////////////////////////////////
                        //                                     //
                        //        PaymentSetup page render     //
                        //                                     //
                        /////////////////////////////////////////
    
                function RenderPaymentSetupPage(&$core, &$render, &$db){

                   $acount = $this->getallcd($this->getSessionCc(),$db);
                                  $acount[balance] = " $ ".number_format( $acount[balance], 2, '.', ' ');
                   $render->assign("acount",      $acount);       
                   $render->assign("exp_m",       substr($acount['client_ccexpdate'],0,2));
                   $render->assign("exp_y",       substr($acount['client_ccexpdate'],2,2));
       
                   $this->RenderRegisterPage($core, $render, $db);
                }


/******************************************************************************************************************/
/************ Render Client Orders page ***************************************************************************/
/******************************************************************************************************************/

                        /////////////////////////////////////////
                        //                                     //
                        //        Client Orders page render    //
                        //                                     //
                        /////////////////////////////////////////
    
function RenderClientOrders(&$core, &$render, &$db)
{
    $acount = $this->getallcd($this->getSessionCc(),$db);
    $render->assign("acount", $acount);       

//-------------- Get Orders ----------------------
    $sql = "select o.id, o.pubdate, o.price, os.name as `status`, o.order_tn, o.provider
                   from orders o, clients_orders co inner join order_status os on (o.`status` = os.id)
                   where o.id = co.order_id and co.cl_id=" . $this->getSessionCc() . " and o.type_order = 'ord'
                   order by o.`status` asc";

    $orders = ArrayDb2Str($db->getAll($sql));
    if(count($orders) > 0){ 
        foreach($orders as $ind => $order)
        {
            $sql = "select shipment.shipment_title from shipment, orders where orders.id = {$order[id]} and shipment.shipment_id = orders.shipment";
            $orders[$ind]['shipment'] = db2str($db->getOne($sql));
            $orders[$ind]['price'] = @number_format($orders[$ind]['price'],2,'.',',');
        }
    }
        else{
    $render->assign("no_orders", 'true');
        }

//    debug($orders);
    $render->assign("orders", $orders);

//-------------- Get Orders return ----------------------
    $sql = "select orders.id, orders.pubdate, orders.price, order_status.name as status, orders.order_tn, orders.provider
            from orders, clients_orders, order_status
            where clients_orders.cl_id = " . $this->getSessionCc() . " and clients_orders.order_id = orders.id
            and orders.status = order_status.id and orders.type_order = 'ret'
            order by orders.status asc";
    
    $returns = ArrayDb2Str($db->getAll($sql));
        foreach($returns as $ind => $order)
    {
        $sql = "select shipment.shipment_title from shipment, orders where orders.id = {$order[id]} and shipment.shipment_id = orders.shipment";
        $returns[$ind]['shipment'] = db2str($db->getOne($sql));
        $returns[$ind]['price'] = @number_format($returns[$ind]['price'],2,'.',',');
    }
//    debug($returns);
    $render->assign("returns", $returns);
}

/******************************************************************************************************************/

                        /////////////////////////////////////////
                        //                                     //
                        //        Static pages                 //
                        //                                     //
                        /////////////////////////////////////////

                function RenderStatic() {

                }

                                        /* custom functions begin */

                function is_email_inDb($m,&$db)                 {
                $sql = "select client_id from clients where client_email='".str2db($m)."'";
                $r = db2str($db->getone($sql));
                        if (isset($r) and $r != '' and $r > 0){
                                return $r;
                        }
                        else{
                        return '-1';
                        }
                }

                function checklogin($login,$pass,&$db)          {
                
                $md5_pass = md5($pass);

                $sql = "select client_id from clients where client_login='".str2db($login)."' and client_password='".str2db($md5_pass)."'";
                //debug($sql);
                $r = db2str($db->getone($sql));
                        if (isset($r) and $r != '' and $r > 0){
                                return $r;
                        }
                        else{
                        return '-1';
                        }
                }

                function setSessionCc($n)                               {
                        $_SESSION['cc']['client_id'] = $n;
                }

                function getSessionCc()                                 {
                        $x = $_SESSION['cc']['client_id'];
                        return($x);
                                
                }


/******************************************************************************************************************/
/******************************************************************************************************************/
/******************************************************************************************************************/

                function getallcd($client_id,&$db)                      { /* returns array(db from string) */
                        $sql = "select * from clients where client_id='".str2db($client_id)."'";
                        $r = $db->getrow($sql);
                        $r = Arraydb2str($r);
                        return $r;                      
                }

/******************************************************************************************************************/
/******************************************************************************************************************/
/******************************************************************************************************************/

                function insertcd($cdarray,&$db)                        { /* inserts new record-row in table */

                        $birthdate = $cdarray['client_birthday'];

                        if (isset($cdarray['client_ccexpdate_m']) and isset($cdarray['client_ccexpdate_y'])){
                        if(!is_numeric($cdarray['client_ccexpdate_m']) or $cdarray['client_ccexpdate_m'] > 12)
                        $cdarray['client_ccexpdate_m'] = 01;
                        if(!is_numeric($cdarray['client_ccexpdate_y']))
                        $cdarray['client_ccexpdate_y'] = 05;
                
                        $cdarray['client_ccexpdate'] = $cdarray['client_ccexpdate_m'].$cdarray['client_ccexpdate_y'];
                        }
                        else{
                        $cdarray['client_ccexpdate'] = 0105;
                        }
                        
                        unset($cdarray['client_ccexpdate_m'],$cdarray['client_ccexpdate_y']);
/*
                        if(!is_numeric($cdarray['client_ccexpdate']))
                                $cdarray['client_ccexpdate'] = '0101';                          
*/
                         if(isne($birthdate) and $birthdate != ''){
                $timest = getdate(strtotime($birthdate));
                $gm = gmdate ("Y-m-d",$timest[0]);
                                $cdarray['client_birthday'] = $gm;
                
                         }
                         
/*                       if(isne($expdate) and $expdate != ''){
                $timest = getdate(strtotime($expdate));
                $gm = gmdate ("Y-m-d",$timest[0]);
                                $cdarray['client_ccexpdate'] = $gm;
                         }
*/
                        $pass = $cdarray['client_password'];
                        $cdarray['client_password'] = md5($pass);                       

                        foreach ($cdarray as $k => $v){
                                $keys .=($keys=="" ? "" : ", ")."{$k}";
                                $vars .=($vars=="" ? "" : ", ")."'".str2db($v)."'";
                        }


                        $sql  ="insert into clients ({$keys}) values({$vars}) ";
                        $sql1 = "select client_id from clients where client_email='".$cdarray['client_email']."'";
                        $check = db2str($db->getone($sql1));

                        if ($check == '' and empty($check) and !is_numeric($check))
                        {
                        $r = $db->Exec($sql);                           /* -1 means dublicate entry (NO! same emails alowed) */
                        return($r);
                        }
                        else                            
                        {
                        return('-1');
                        }

                }

/******************************************************************************************************************/
/******************************************************************************************************************/
/******************************************************************************************************************/

                function updatecd($client_id,$cdarray,&$db)             { /* update selected record with new data*/

                        $birthdate = $cdarray['client_birthday'];

                        $cdarray['client_ccexpdate'] = $cdarray['client_ccexpdate_m'].$cdarray['client_ccexpdate_y'];
                        unset($cdarray['client_ccexpdate_m'],$cdarray['client_ccexpdate_y']);
                        if(!is_numeric($cdarray['client_ccexpdate']))
                                $cdarray['client_ccexpdate'] = '0101';                          

                         if(isne($birthdate)){
                $timest = getdate(strtotime($birthdate));
                $gm = gmdate ("Y-m-d",$timest[0]);
                                $cdarray['client_birthday'] = $gm;
                
                         }
/*                       
                         if(isne($expdate)){
                $timest = getdate(strtotime($expdate));
                $gm = gmdate ("Y-m-d",$timest[0]);
                                $cdarray['client_ccexpdate'] = $gm;
                         }
*/
                        $set = '';

                        if (in_array('client_password', array_keys($cdarray))){
                                $pass = $cdarray['client_password'];
                                $cdarray['client_password'] = md5($pass);                                                       
                        }
                        

                        foreach ($cdarray as $k => $v) {
                                $set .= ($set == "" ? "" : ", ")."{$k} = '".str2db($v)."'";
                        }
                        $sql = "update clients set {$set} where client_id='".str2db($client_id)."'";
                        $r = $db->Exec($sql);
                        return $r;
                }

/******************************************************************************************************************/
/******************************************************************************************************************/
/******************************************************************************************************************/

                function deletecd($client_id,&$db)              { /* delete client record from table */

                        $sql = "delete from clients where client_id='".str2db($client_id)."'";
                        $r = $db->Exec($sql);
                        return $r;
                }

/******************************************************************************************************************/
/******************************************************************************************************************/
/******************************************************************************************************************/


                function setmsgbox($msg)                        { /* simple messaging between pages */
                $_SESSION['msg_box'] = str2db($msg);
                }

                function getmsgbox()                            { /* simple messaging between pages */
                return($_SESSION['msg_box']);
                }

                function unsetmsgbox()                          { /* trash simple messaging between pages */
                $_SESSION['msg_box'] = '';
                
                }


                function getnonameclientid(&$db){
                        $noname = $this->getnonameclientname();
                        $r = $db->getone("select client_id from clients where client_name = '$noname'");
                        if($r > 0){
                                
                        }
                        else{
                                $r = $db->exec("insert into clients (client_name) values ('$noname')");
                        }
                        return ($r);
                }

                function getnonameclientname(){
                        $name = 'noone';
                        return($name);
                }
        // ----------------------------------------------------------------------------------
        // --- [ GET IMAGES SIZE ] ----------------------------------------------------------
        // ----------------------------------------------------------------------------------

        function getimgsizes($froot,$img){ 
                if(isne($img) && is_file($froot.'/inventory/'.$img)) {
                        $img = $froot.'/inventory/'.$img;
                        $ar = getimagesize($img);
                        $arrr = $ar[0].','.($ar[1]+50);
                        return $arrr;
                }
                return "";
        } 
        

};


?>
